import { connect } from 'react-redux';
import React, { Component } from 'react';
import Amount from '../component/amount';
import 'styles/expense/expense-amount.scss';
import ExpenseService from '../expense-service';
import shallowEqual from '../component/shallowEqual';
import SubsidyModal from 'containers/expense/component/subsidy-modal';

@connect(mapStateToProps)
class ExpenseAmount extends Component {

  static contextTypes = {
    annotates: React.PropTypes.array,
    isWaitForAudit: React.PropTypes.bool,
    currentExpense: React.PropTypes.object,
    expenseReport: React.PropTypes.object,
    currentExpenseType: React.PropTypes.object,
    amountData: React.PropTypes.array
  };

  constructor(props, context){
    super(props,context);
    this.state = {
      ...this.initData(context)
    }
  }


  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return !shallowEqual(this.props, nextProps) ||
      !shallowEqual(this.state, nextState) ||
      !shallowEqual(this.context.amountData, nextContext.amountData);
  }

  componentWillReceiveProps(nextProps,nextContext) {
    nextProps.randomHash !== this.props.randomHash && this.setState(this.initData(nextContext));
  }


  initData = (context) => {
    const { annotates } = context;
    return {
      annotates: annotates
    };
  };

  handleAnnotate = async () => {
    const { currentExpense: { invoiceOID } } = this.context;
    const annotates = await ExpenseService.getAnnotate(invoiceOID);
    this.setState({ annotates });
  };

  handleShowMore = () => {
    const { expenseReport: { baseCurrency, withTime }, currentExpense, currentExpense: { invoiceOID, mileageAllowanceExpenseV2DTO: mileageAllowance }, amountData: { allowanceAmount }  } = this.context;
    SubsidyModal.open({
      invoiceOID,
      baseCurrency,
      withTime,
      mileageAllowance,
      allowanceAmount,
      currentExpense
    }, this);
  };

  render() {
    const { isWaitForAudit, currentExpense, amountData } = this.context;
    const { annotates } = this.state;
    const { loginUser } = this.props;
    return (
      <section className="expense-amount">
        <Amount
          currentExpense={currentExpense}
          handleShowMore={this.handleShowMore}
          amount={amountData}
          loginUser={loginUser}
          annotates={annotates}
          isWaitForAudit={isWaitForAudit}
          refreshAnnotate={this.handleAnnotate}
        />
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  };
}


export default ExpenseAmount;
